<?php

namespace backend\modules\home\models;

use Yii;

/**
 * This is the model class for table "category".
 *
 * @property int $id
 * @property int $cid
 * @property string $title
 * @property string $code
 * @property int $sort
 * @property int $created_at
 * @property int $updated_at
 * @property string $icon
 * @property int $count
 * @property int $is_top_show
 * @property int $is_footer_show
 */
class Category extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'lw_category';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cid', 'title'], 'required'],
            [['cid', 'sort', 'created_at', 'updated_at', 'count'], 'integer'],
            [['title'], 'string', 'max' => 100],
            [['code'], 'string', 'max' => 64],
            [['icon'], 'string', 'max' => 50],
            [['is_top_show', 'is_footer_show'], 'string', 'max' => 1],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'cid' => '类别',
            'title' => '标题',
            'code' => '路由',
            'sort' => '排序',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'icon' => '图标',
            'count' => '点击量',
            'is_top_show' => '是否在顶部菜单显示',
            'is_footer_show' => '是否在尾部菜单显示',
        ];
    }

    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){
                $this->created_at = time();
                $this->updated_at = time();
                $this->count = 0;
                $this->icon = '';
                if(empty($this->sort)){
                    $this->sort = 0;
                }
                if(empty($this->is_top_show)){
                    $this->is_top_show = 0;
                }
                if(empty($this->is_footer_show)){
                    $this->is_footer_show = 0;
                }
            }

            $this->updated_at = time();
            return true;
        }
        return false;
    }
}
